//
//  LoginViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/7/26.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "LoginViewController.h"
#import "SignUpViewController.h"

#import "TabBarViewController.h"

#import "UIImage+GradientColor.h"
#import "WXApi.h"

@interface LoginViewController ()<UITextFieldDelegate>

@property (nonatomic,strong) UITextField *phoneField;
@property (nonatomic,strong) UITextField *pswField;
@property (nonatomic,strong) UITextField *codeField;
@property (nonatomic,strong) UIButton *loginBtn;

@property (nonatomic,assign) BOOL isCode;

@property (nonatomic,assign) NSInteger verCodeTime;
@property (nonatomic,strong) NSTimer *verCodeTimer;//验证码计时器
@property (nonatomic,strong) UIButton *verCodeBtn;//发送验证码按钮

@end

@implementation LoginViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.isCode = NO;
    [self setUI];
    self.view.backgroundColor = [UIColor whiteColor];
    [kNotificationCenter addObserver:self selector:@selector(wechatLogin:) name:@"WechatLogin" object:nil];
}

- (void)dealloc {
    [self.verCodeTimer invalidate];
    self.verCodeTimer = nil;
    [kNotificationCenter removeObserver:self name:@"WechatLogin" object:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)setUI {
    UIImageView *logo = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(81)) / 2, STATUS_BAR_HEIGHT + ScreenX375(22), ScreenX375(81), ScreenX375(80))];
    logo.image = ImageWithName(@"虾拼 logo");
    [self.view addSubview:logo];
    
    UIImageView *logoNote = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(214)) / 2, ScreenX375(112) + STATUS_BAR_HEIGHT, ScreenX375(214), ScreenX375(14))];
    logoNote.image = ImageWithName(@"标语");
    [self.view addSubview:logoNote];
    
    UIView *phoneLeft = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(30), ScreenX375(37))];
    UIImageView *phoneImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, ScreenX375(7), ScreenX375(14), ScreenX375(20))];
    phoneImg.image = ImageWithName(@"手机");
    [phoneLeft addSubview:phoneImg];
    
    self.phoneField = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(37), ScreenX375(218) + STATUS_BAR_HEIGHT, SCREEN_WIDTH - ScreenX375(74), ScreenX375(37))];
    self.phoneField.font = Kfont(17);
    self.phoneField.placeholder = @"请输入手机号码";
    self.phoneField.leftView = phoneLeft;
    self.phoneField.text = @"15757166497";
    self.phoneField.clearsOnBeginEditing = NO;
    self.phoneField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.phoneField.leftViewMode = UITextFieldViewModeAlways;
    self.phoneField.keyboardType = UIKeyboardTypePhonePad;
    [self.phoneField addTarget:self action:@selector(changeText:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:self.phoneField];
    
    UIView *pswLeft = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(30), ScreenX375(37))];
    UIImageView *pswImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, ScreenX375(9), ScreenX375(14), ScreenX375(18))];
    pswImg.image = ImageWithName(@"密码");
    [pswLeft addSubview:pswImg];
    
    self.pswField = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(37), ScreenX375(287) + STATUS_BAR_HEIGHT, SCREEN_WIDTH - ScreenX375(74), ScreenX375(37))];
    self.pswField.font = Kfont(17);
    self.pswField.placeholder = @"请输入密码";
    self.pswField.leftView = pswLeft;
    self.pswField.clearsOnBeginEditing = NO;
    self.pswField.hidden = self.isCode;
    self.pswField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.pswField.leftViewMode = UITextFieldViewModeAlways;
    self.pswField.secureTextEntry = YES;
    self.pswField.returnKeyType = UIReturnKeyDone;
    self.pswField.delegate = self;
    [self.pswField addTarget:self action:@selector(changeText:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:self.pswField];
    
    UIImage *bgImg = [UIImage gradientColorImageFromColors:@[REXADECIMALCOLOR(@"#cccccc"),REXADECIMALCOLOR(@"#cccccc")] gradientType:GradientTypeLeftToRight imgSize:CGSizeMake(ScreenX375(80), ScreenX375(24))];
    UIView *codeRight = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(80), ScreenX375(37))];
    _verCodeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, ScreenX375(6), ScreenX375(80), ScreenX375(24))];
    [_verCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_verCodeBtn setTitleColor:REXADECIMALCOLOR(@"#ffffff") forState:UIControlStateNormal];
    _verCodeBtn.titleLabel.font = Kfont(12);
    [_verCodeBtn addTarget:self action:@selector(sendVerCode:) forControlEvents:UIControlEventTouchUpInside];
    [_verCodeBtn setBackgroundImage:bgImg forState:UIControlStateNormal];
    _verCodeBtn.layer.cornerRadius = ScreenX375(12);
    _verCodeBtn.clipsToBounds = YES;
    [codeRight addSubview:_verCodeBtn];
    
    UIView *codeLeft = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(30), ScreenX375(37))];
    UIImageView *codeImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, ScreenX375(9), ScreenX375(16), ScreenX375(18))];
    codeImg.image = ImageWithName(@"验证 验证码");
    [codeLeft addSubview:codeImg];
    
    self.codeField = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(37), ScreenX375(287) + STATUS_BAR_HEIGHT, SCREEN_WIDTH - ScreenX375(74), ScreenX375(37))];
    self.codeField.font = Kfont(17);
    self.codeField.leftView = codeLeft;
    self.codeField.placeholder = @"请输入验证码";
    self.codeField.leftViewMode = UITextFieldViewModeAlways;
    self.codeField.rightView = codeRight;
    self.codeField.rightViewMode = UITextFieldViewModeAlways;
    self.codeField.keyboardType = UIKeyboardTypePhonePad;
    self.codeField.hidden = !self.isCode;
    [self.codeField addTarget:self action:@selector(changeText:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:self.codeField];
    
    for (int i = 0; i < 2; i++) {
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(ScreenX375(37), ScreenX375(255) + STATUS_BAR_HEIGHT + i * ScreenX375(68), SCREEN_WIDTH - ScreenX375(74), 0.5)];
        line.backgroundColor = LineColor;
        [self.view addSubview:line];
    }
    
    UIButton *changeTypeBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(30), ScreenX375(340) + STATUS_BAR_HEIGHT, ScreenX375(64), ScreenX375(22))];
    [changeTypeBtn setTitle:@"快捷登录" forState:UIControlStateNormal];
    [changeTypeBtn setTitleColor:REXADECIMALCOLOR(@"#b2b2b2") forState:UIControlStateNormal];
    changeTypeBtn.titleLabel.font = Kfont(14);
    [changeTypeBtn addTarget:self action:@selector(changeType:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:changeTypeBtn];
    
    UIButton *signUpBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - ScreenX375(82), ScreenX375(340) + STATUS_BAR_HEIGHT, ScreenX375(52), ScreenX375(22))];
    [signUpBtn setTitle:@"注册" forState:UIControlStateNormal];
    [signUpBtn setTitleColor:REXADECIMALCOLOR(@"#fe494d") forState:UIControlStateNormal];
    signUpBtn.titleLabel.font = Kfont(15);
    [signUpBtn addTarget:self action:@selector(signUp) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:signUpBtn];
    
    self.loginBtn = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(193)) / 2, ScreenX375(400) + STATUS_BAR_HEIGHT, ScreenX375(193), ScreenX375(103))];
    [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    self.loginBtn.titleLabel.font = Kfont(18);
    [self.loginBtn setTitleColor:REXADECIMALCOLOR(@"#ffffff") forState:UIControlStateNormal];
    self.loginBtn.titleEdgeInsets = UIEdgeInsetsMake(-5, 0, 5, 0);
    [self.loginBtn setBackgroundImage:ImageWithName(@"按钮1") forState:UIControlStateNormal];
    [self.loginBtn addTarget:self action:@selector(loginClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.loginBtn];
    
    if ([WXApi isWXAppInstalled]) {
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(ScreenX375(104), ScreenX375(561) + STATUS_BAR_HEIGHT, SCREEN_WIDTH - ScreenX375(208), 1)];
        line.backgroundColor = REXADECIMALCOLOR(@"#d8d8d8");
        [self.view addSubview:line];
        
        UILabel *thirdNote = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(86)) / 2, ScreenX375(553) + STATUS_BAR_HEIGHT, ScreenX375(86), ScreenX375(16))];
        thirdNote.text = @"第三方登录";
        thirdNote.font = Kfont(14);
        thirdNote.backgroundColor = [UIColor whiteColor];
        thirdNote.textAlignment = NSTextAlignmentCenter;
        thirdNote.textColor = REXADECIMALCOLOR(@"#999999");
        [self.view addSubview:thirdNote];
        
        UIButton *thirdBtn = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - ScreenX375(37)) / 2, ScreenX375(582) + STATUS_BAR_HEIGHT, ScreenX375(37), ScreenX375(37))];
        [thirdBtn setImage:ImageWithName(@"微信") forState:UIControlStateNormal];
        [thirdBtn addTarget:self action:@selector(thirdLogin) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:thirdBtn];
    }
}

- (void)thirdLogin {
    ///微信登录
    //构造SendAuthReq结构体
    SendAuthReq* req =[[SendAuthReq alloc ] init];
    req.scope = @"snsapi_userinfo" ;
    req.state = @"123" ;
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req];
}

- (void)changeType:(UIButton *)button {
    self.isCode = !self.isCode;
    self.pswField.hidden = self.isCode;
    self.codeField.hidden = !self.isCode;
    self.pswField.text = @"";
    self.codeField.text = @"";
    if (self.isCode) {
        [button setTitle:@"密码登录" forState:UIControlStateNormal];
    }else {
        [button setTitle:@"快捷登录" forState:UIControlStateNormal];
    }
}

- (void)changeText:(UITextField *)textField {
    if (textField == self.phoneField) {
        if (self.phoneField.text.length == 11) {
            UIImage *bgImg = [UIImage gradientColorImageFromColors:@[REXADECIMALCOLOR(@"#ff1061"),REXADECIMALCOLOR(@"#fd4c4e")] gradientType:GradientTypeLeftToRight imgSize:CGSizeMake(ScreenX375(80), ScreenX375(24))];
            [_verCodeBtn setBackgroundImage:bgImg forState:UIControlStateNormal];
            
            if (self.codeField.text.length > 0 || self.pswField.text.length > 0) {
                [self.loginBtn setBackgroundImage:ImageWithName(@"按钮2") forState:UIControlStateNormal];
            }else {
                [self.loginBtn setBackgroundImage:ImageWithName(@"按钮1") forState:UIControlStateNormal];
            }
        }else {
            UIImage *bgImg = [UIImage gradientColorImageFromColors:@[REXADECIMALCOLOR(@"#cccccc"),REXADECIMALCOLOR(@"#cccccc")] gradientType:GradientTypeLeftToRight imgSize:CGSizeMake(ScreenX375(80), ScreenX375(24))];
            [_verCodeBtn setBackgroundImage:bgImg forState:UIControlStateNormal];
            [self.loginBtn setBackgroundImage:ImageWithName(@"按钮1") forState:UIControlStateNormal];
        }
    }else {
        if (textField.text.length > 0 && self.phoneField.text.length == 11) {
            [self.loginBtn setBackgroundImage:ImageWithName(@"按钮2") forState:UIControlStateNormal];
        }else {
            [self.loginBtn setBackgroundImage:ImageWithName(@"按钮1") forState:UIControlStateNormal];
        }
    }
}

- (void)signUp {
    SignUpViewController *vc = [[SignUpViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)loginClick {
    if (self.phoneField.text.length != 11) {
        [HttpManager showNoteMsg:@"请输入正确的手机号"];
        return;
    }
    if (self.isCode) {
        if (self.codeField.text.length == 0) {
            [HttpManager showNoteMsg:@"请输入验证码"];
            return;
        }
    }else {
        if (self.pswField.text.length == 0) {
            [HttpManager showNoteMsg:@"请输入密码"];
            return;
        }
    }
    [HttpManager showWait];
    NSString *url = [NSString stringWithFormat:@"%@api/phoneLogin",REQUESTHEADER];
    NSDictionary *parameter = @{@"phone":self.phoneField.text,@"code":self.codeField.text};
    if (!self.isCode) {
        url = [NSString stringWithFormat:@"%@api/login",REQUESTHEADER];
        parameter = @{@"phone":self.phoneField.text,@"password":self.pswField.text};
    }
    [HttpManager postHttpRequestByGet:url andParameter:parameter success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        [HttpManager hideWait];
        if ([status isEqualToString:@"200"]) {
            NSString *authorization = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"Authorization"]];
            kNSUDefaultSaveVauleAndKey(authorization, @"Authorization");

            NSString *userId = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"id"]];
            kNSUDefaultSaveVauleAndKey(userId, @"userId");
            
            NSString *nickName = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"nickName"]];
            kNSUDefaultSaveVauleAndKey(nickName, @"nickName");
            
            NSString *intro = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"intro"]];
            kNSUDefaultSaveVauleAndKey(intro, @"intro");
            
            NSString *pic = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"pic"]];
            kNSUDefaultSaveVauleAndKey(pic, @"pic");
            
            NSString *inviteCode = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"inviteCode"]];
            kNSUDefaultSaveVauleAndKey(inviteCode, @"inviteCode");

            NSString *birthday = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"birthday"]];
            kNSUDefaultSaveVauleAndKey(birthday, @"birthday");

            NSString *qrCode = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"qrCode"]];
            kNSUDefaultSaveVauleAndKey(qrCode, @"qrCode");

            NSString *sex = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"sex"]];
            kNSUDefaultSaveVauleAndKey(sex, @"sex");
            
            [kUserDefaults synchronize];

            kKeyWindow.rootViewController = [[TabBarViewController alloc] init];
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"message"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

//发送验证码
- (void)sendVerCode:(UIButton *)sender
{
    if (self.phoneField.text.length != 11) {
        [HttpManager showNoteMsg:@"请输入正确的手机号"];
        return;
    }
    
    [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@api/sendSms",REQUESTHEADER] andParameter:@{@"phone":self.phoneField.text} success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        if ([status isEqualToString:@"200"]) {
            if (successResponse[@"data"][@"code"]) {
                NSLog(@"code:%@",successResponse[@"data"][@"code"]);
            }
            self.codeField.text = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"code"]];
            self.verCodeTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerCountAction) userInfo:nil repeats:YES];
            self.verCodeTime = 60;
            [self.verCodeTimer fire];
            UIImage *bgImg = [UIImage gradientColorImageFromColors:@[REXADECIMALCOLOR(@"#cccccc"),REXADECIMALCOLOR(@"#cccccc")] gradientType:GradientTypeLeftToRight imgSize:CGSizeMake(ScreenX375(80), ScreenX375(24))];
            [self.verCodeBtn setBackgroundImage:bgImg forState:UIControlStateNormal];
            self.verCodeBtn.enabled = NO;
            
        }else {
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"message"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (void)timerCountAction
{
    self.verCodeTime--;
    
    [self.verCodeBtn setTitle:[NSString stringWithFormat:@"%ld秒后重发",(long)self.verCodeTime] forState:UIControlStateNormal];
    if (self.verCodeTime == 0) {
        UIImage *bgImg = [UIImage gradientColorImageFromColors:@[REXADECIMALCOLOR(@"#ff1061"),REXADECIMALCOLOR(@"#fd4c4e")] gradientType:GradientTypeLeftToRight imgSize:CGSizeMake(ScreenX375(80), ScreenX375(24))];
        [_verCodeBtn setBackgroundImage:bgImg forState:UIControlStateNormal];
        self.verCodeBtn.enabled = YES;
        [self.verCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.verCodeTimer invalidate];
        self.verCodeTimer = nil;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return NO;
}

#pragma mark - 微信登录
- (void)wechatLogin:(NSNotification *)aNotification{
    NSString *code = aNotification.object[@"code"];
    [HttpManager showWait];
    [HttpManager postHttpRequestByGet:[NSString stringWithFormat:@"%@api/wxLogin",REQUESTHEADER] andParameter:@{@"code":code} success:^(id successResponse) {
        [HttpManager hideWait];
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"code"]];
        if ([status isEqualToString:@"4001"]) {
            SignUpViewController *vc = [[SignUpViewController alloc] init];
            vc.openId = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"data"][@"openid"]];
            [self.navigationController pushViewController:vc animated:YES];
        }else if ([status isEqualToString:@"200"]) {
            NSString *authorization = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"Authorization"]];
            kNSUDefaultSaveVauleAndKey(authorization, @"Authorization");
            
            NSString *userId = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"id"]];
            kNSUDefaultSaveVauleAndKey(userId, @"userId");
            
            NSString *nickName = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"nickName"]];
            kNSUDefaultSaveVauleAndKey(nickName, @"nickName");
            
            NSString *intro = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"intro"]];
            kNSUDefaultSaveVauleAndKey(intro, @"intro");
            
            NSString *pic = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"pic"]];
            kNSUDefaultSaveVauleAndKey(pic, @"pic");
            
            NSString *inviteCode = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"inviteCode"]];
            kNSUDefaultSaveVauleAndKey(inviteCode, @"inviteCode");
            
            NSString *birthday = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"birthday"]];
            kNSUDefaultSaveVauleAndKey(birthday, @"birthday");
            
            NSString *qrCode = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"qrCode"]];
            kNSUDefaultSaveVauleAndKey(qrCode, @"qrCode");
            
            NSString *sex = [NSString stringWithFormat:@"%@",successResponse[@"data"][@"user"][@"sex"]];
            kNSUDefaultSaveVauleAndKey(sex, @"sex");
            
            [kUserDefaults synchronize];
            
            kKeyWindow.rootViewController = [[TabBarViewController alloc] init];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
